<?php
namespace ITSociaal\Themes\Houtgrutter\Includes;

use ITSociaal\Themes\Houtgrutter\PostProcessorInterface;
use ITSociaal\Themes\Houtgrutter\TemplateProcessor;
use ITSociaal\Themes\Houtgrutter\WordPressBase;

class HelperMainMenu extends WordPressBase implements PostProcessorInterface
{
	const MAIN_MENU = 3;  // Hoofdmenu ID
	const SHOP_MENU = 17; // Webshopmenu ID

	/**
	 * Removes substring if it occurs at the end of $string
	 *
	 * @param string $string Original string
	 * @param string $remove Substring to remove
	 *
	 * @return string without $remove if found at end
	 */
	protected function removeStringFromEnd($string, $remove)
	{
		$pos = strrpos($string, $remove);

		if ($pos === false) {
			return $string;
		}

		return ($pos + strlen($remove) === strlen($string))
			? substr($string, 0, $pos)
			: $string;
	}

	/**
	 * Removes </ul> and </div> from end of $html
	 *
	 * @param string $html
	 *
	 * @return string
	 */
	protected function reopenNavMenu($html)
	{
		return
			$this->removeStringFromEnd(
				trim($this->removeStringFromEnd(trim($html), "</div>")),
				"</ul>"
			);
	}

	/**
	 * Get HTML for site logo
	 *
	 * @return string
	 */
	public function getLogo()
	{
		$wp = $this->getWP();

		return '<h1 id="logo"><img width="300" height="61" src="'
			. $wp->avia_get_option("logo")
			. '" alt="'
			. $wp->get_bloginfo("name")
			. '" /></h1>';
	}

	/**
	 * Get HTML for the main menu
	 *
	 * @return string
	 */
	public function getMainMenu()
	{
		return trim($this->reopenNavMenu($this->getWP()->wp_nav_menu([
			"container"		=> "div",
			"container_class" => "mainmenu container",
			"depth"			=> 1,
			"echo"			=> false,
			"fallback_cb"	=> false,
			"menu"			=> static::MAIN_MENU,
			"menu_id"		=> "MainMenu",
		])));
	}

	/**
	 * Get HTML for the webshop menubar
	 *
	 * @return string
	 */
	public function getShopMenu()
	{
		return trim($this->reopenNavMenu($this->getWP()->wp_nav_menu([
			"container"		=> "div",
			"container_class" => "shopmenu hidez",
			"depth"			=> 1,
			"echo"			=> false,
			"fallback_cb"	=> false,
			"menu"			=> static::SHOP_MENU,
			"menu_id"		=> "ShopMenu",
			"menu_class"	=> "container",
		])));
	}

	/**
	 * Get HTML for the search form
	 *
	 * @return string
	 */
	public function getSearch()
	{
		return $this->getWP()->avia_append_search_nav(
			"",
			(object)["theme_location" => "avia"]
		);
	}

	/**
	 * Get HTML for the subtotal
	 *
	 * @return string
	 */
	public function getCartSubtotal()
	{
		return $this->getWP()->shopp(
			"cart",
			"subtotal",
			["echo" => false, "return" => true]
		);
	}

	/** {@inheritDoc} */
	public function post($content, TemplateProcessor $tp=null)
	{
		$tp = $tp ?: new TemplateProcessor;

		return $tp->setContext($this)->process($content);
	}
}

/* vi:set ts=4 sw=4 noet: */
